package com.guxingke.gsb.util;

import com.guxingke.gsb.Gsb;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.nio.file.FileSystems;

/**
 * Created by 孤星可 on 2015/11/22.
 *
 * @author guxingke
 * @since 2015/11/22
 */
public class PathUtil {
    public static final String SYSTEM_SEPARATOR = File.separator;
    public static final String USER_PATH = System.getProperty("user.dir");
    public static final String LINE_SEPARATOR = System.getProperty("line.separator");
    public static final boolean IS_WINDOWS = System.getProperty("os.name").contains("indow");

    public static String pathCheck(String path) {
        if (IS_WINDOWS) {
            if (path.startsWith("\\") || path.startsWith("/")) {
                return path.substring(1);
            }
        }
        return path;
    }

    public static String getSystemPathSpit() {
        if (IS_WINDOWS) {
            return "\\\\";
        } else {
            return "/";
        }
    }

    public static String getClassRootPath() {
        String basePath = Gsb.getInstance().getClass().getProtectionDomain().getCodeSource().getLocation().getPath();
        try {
            basePath = URLDecoder.decode(basePath, "utf-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        System.out.println("basePath:" + basePath);
        if (basePath.endsWith(".jar")) {
            basePath = basePath.substring(0, basePath.lastIndexOf("/") + 1);
        }
        File f = new File(basePath);
        basePath = f.getAbsolutePath();
        return pathCheck(basePath);
    }

    public static String toJavaPath(String path) {
        // 反斜杠"\"转化为"/".
        if (path.contains("\\")) {
            return path.replaceAll("\\\\", "/");
        }
        return path;
    }
}
